import './ElectronicFence.scss'
import { useRef, useState } from 'react'
import { useMount } from 'ahooks'
import { useRequest } from 'alova/client'
import { Button, Tooltip, App, } from "antd"
import * as mars3d from "mars3d"
import { updateTreeByKey } from '../../Utils/Common'
import { v4 } from 'uuid'

import {
    CloseOutlined,
    PlusOutlined,
    EnvironmentOutlined,
    DeleteOutlined,
    SaveOutlined,
    EditOutlined
} from '@ant-design/icons'


import { Http } from '../../API'
// import { Initialization } from '../../Map/InitFunc'
import { InitMars3dMap } from '../../Utils/Mars3dConfig'
import { dataMap } from '../../Utils/Mars3dParams'


const wallStyle = {
    color: "#13c2c2",
    width: 2,
    closure: true,
}



const ElectronicFence = () => {
    const { message, notification } = App.useApp();
    const MapBox = useRef()
    const [Map, setMap] = useState()
    const [Gra, setGra] = useState()
    const [Open, setOpen] = useState(false)
    const [ListData, setListData] = useState([])

    const [ProjectStatus, setProjectStatus] = useState()
    const [ActiveProject, setActiveProject] = useState()


    const [FenceCoordinate, setFenceCoordinate] = useState([])

    const items = [
        { text: "项目列表", callback: () => setOpen(true) }
    ]

    const { send } = useRequest(data => Http(data), { immediate: false })
    useMount(() => {
        const { map, gra } = InitMars3dMap({ BOX: MapBox.current, DATA: dataMap })
        map.bindContextMenu(items)
        setMap(map)
        setGra(gra)
        getData(gra)
    })

    const getData = (gra) => {
        gra.clear()
        send({ url: 'getTransportProjects', params: { pageIndex: 1, pageSize: 10000 } }).then(res => {
            setListData(res.list)
            if (!ActiveProject) getFence(res.list[0].uuid, gra)
            res.list.forEach(item => {
                if (item.lng && item.lat) {
                    const { uuid, type, alias, lng, lat } = item
                    gra.addGraphic(new mars3d.graphic.PointPrimitive({
                        id: uuid,
                        position: [lng, lat, 0],
                        style: {
                            color: "#13c2c2",
                            pixelSize: 8,
                            outlineColor: "#ffffff",
                            outlineWidth: 2,
                            clampToGround: true,
                            label: { text: `[${type}] ${alias}`, font_size: 24, color: "#262626", outline: true, outlineColor: "#fff", pixelOffsetY: -40 }
                        }
                    }))
                }
            })
        })
    }


    const getFence = (uuid, gra) => {
        const GRA = gra || Gra
        send({ url: 'getFenceCoordinate', params: { projectGuid: uuid } }).then(res => {
            setFenceCoordinate(res.list)
            setActiveProject(uuid)
            const graphics = GRA.getGraphicsByAttr('poly', 'attr')
            graphics.forEach(graphic => GRA.removeGraphic(graphic))

            res.list.forEach(item => {
                const { guid, fenceCoordinates } = item
                if (GRA.getGraphicById(guid)) GRA.removeGraphic(Gra.getGraphicById(guid))
                const poly = new mars3d.graphic.PolylineEntity({ id: guid, attr: 'poly', positions: JSON.parse(fenceCoordinates), style: wallStyle })
                GRA.addGraphic(poly)
            })
        })
    }


    const onAddProject = (item) => {
        const { uuid, type, alias } = item
        Gra.startDraw({
            type: "point",
            style: {
                color: "#13c2c2",
                pixelSize: 8,
                outlineColor: "#ffffff",
                outlineWidth: 2,
                clampToGround: true,
                label: { text: `[${type}] ${alias}`, font_size: 24, color: "#262626", outline: true, outlineColor: "#fff", pixelOffsetY: -40 }
            }
        }).then(res => {
            const [lng, lat] = res.coordinate
            const params = { uuid, lng, lat }
            send({ url: 'posTransportProjects', params }).then(res => {
                message.success({ content: '项目定位信息添加成功!', key: 'message' })
                getData(Gra)
            })
        })
    }

    // 定位项目
    const onLocation = (uuid) => {
        Map.flyToGraphic(Gra.getGraphicById(uuid), { radius: 100000 })
    }
    // 修改定位
    const onModifyProject = (uuid) => {
        if (!ProjectStatus) {
            setProjectStatus(uuid)
            message.loading({ content: '项目定位信息更改中...', duration: 0, key: 'message' })
            Gra.startEditing(Gra.getGraphicById(uuid))
        } else notification.warning({ message: '启动失败!', description: '已有项目修改中.', key: 'notification' })
    }

    const onSaveProject = (uuid) => {
        const { graphics } = Gra.stopEditing()
        const { coordinate } = graphics.find(v => v.id === uuid)
        const [lng, lat] = coordinate
        const params = { uuid, lng, lat }
        send({ url: 'posTransportProjects', params }).then(res => {
            message.success({ content: '项目定位信息修改成功!', key: 'message' })
            setProjectStatus()
        })
    }

    const onAddDraw = (uuid) => {
        const id = v4()
        message.loading({ content: '开始绘制...', key: 'message', duration: 0 })
        Gra.startDraw({ id, type: "polyline", style: wallStyle }).then(res => {
            const params = { uuid: id, name: id, attr: 'poly', projectGuid: uuid, fenceCoordinates: JSON.stringify(res.coordinates) }
            send({ url: 'posAddFences', params })
                .then(() => {
                    message.success({ content: '围栏绘制成功!', key: 'message' })
                    getFence(uuid)
                })
                .catch(() => message.error({ content: '围栏绘制失败!', key: 'message' }))
        })
    }

    const onRemove = (uuid, id) => {
        message.loading({ content: '正在删除...', key: 'fence', duration: 0 })
        send({ url: 'posRemoveFence', params: { fenceGuid: uuid } }).then(res => {
            getFence(id)
            Gra.removeGraphic(Gra.getGraphicById(uuid))
            message.success({ content: '围栏删除成功!', key: 'fence' })
        }).catch(() => message.error({ content: '围栏删除失败!', key: 'fence' }))
    }

    return (
        <div className='ElectronicFence'>
            <div className={`Open animate__animated ${!Open ? 'animate__bounceInLeft' : 'animate__bounceOutLeft'}`}>
                <button className="button" onClick={() => setOpen(true)}>项目列表</button>
            </div>
            <div className='Map' ref={MapBox} />
            <div className={`PerList animate__animated ${Open ? 'animate__bounceInLeft' : 'animate__bounceOutLeft'}`}>
                <div className='Tilte'>
                    <div>项目列表</div>
                    <CloseOutlined onClick={() => setOpen(false)} />
                </div>
                <div className='List'>
                    {ListData.map((item) => {
                        const { uuid, type, name, alias, address, lat, lng, fenceList } = item
                        const status = lat && lng
                        return (
                            <div className='Item' key={uuid}>
                                <div className='Project'>
                                    <div> [{type}]{alias} {address ? `(${address})` : ''}</div>
                                    {ActiveProject === uuid ? <div className='active'>选中项目</div> : <div>{name}</div>}
                                </div>
                                <div className='Options'>
                                    {status && <Button type='link' icon={<EnvironmentOutlined />} onClick={() => onLocation(uuid)}>定位位置信息</Button>}
                                    {status ? ProjectStatus === uuid ?
                                        <Button type='link' danger icon={<SaveOutlined />} onClick={() => onSaveProject(uuid)}>保存位置信息</Button> :
                                        <Button type='link' icon={<EditOutlined />} onClick={() => onModifyProject(uuid)}>修改位置信息</Button> :
                                        <Button type='link' icon={<EditOutlined />} onClick={() => onAddProject(item)}>添加项目定位</Button>
                                    }
                                    {ActiveProject === uuid ?
                                        <Button type='link' icon={<PlusOutlined />} onClick={() => onAddDraw(uuid)}>添加电子围栏</Button> :
                                        <Button type='link' onClick={() => getFence(uuid)}>获取电子围栏</Button>
                                    }
                                </div>
                                {ActiveProject === uuid ?
                                    FenceCoordinate.length === 0 ?
                                        <div className='fenceEmpty'>无电子围栏</div> :
                                        <div className='FenceList'>
                                            {FenceCoordinate.map((item, index) => {
                                                const { guid } = item
                                                return (
                                                    <div key={index}>
                                                        <div>电子围栏-{guid}</div>
                                                        <div>
                                                            <Button type='link' onClick={() => onLocation(guid)}>定位</Button>
                                                            <Button type='link' danger onClick={() => onRemove(guid, uuid)}>删除</Button>
                                                        </div>
                                                    </div>
                                                )
                                            })}
                                        </div> : null
                                }
                            </div>
                        )
                    })}
                </div>
            </div>
        </div>
    );
};

export default ElectronicFence;